// 最牛解法
; (function () {
    //return
    /**
   * @param {string} s
   * @return {number}
   */
    var longestValidParentheses = function (s) {
        let maxLen = 0;
        const stack = [];

        stack.push(-1); // 在栈中预置 -1 作为参照物
        for (let i = 0; i < s.length; i++) {
            if (s[i] === '(') {
                stack.push(i); // 左括号的索引，入栈
            } else { // 遍历到右括号
                stack.pop(); // 栈顶的左括号被匹配，出栈

                if (stack.length) { // 栈未空
                    const curMaxLen = i - stack[stack.length - 1]; // 计算有效连续长度
                    maxLen = Math.max(maxLen, curMaxLen); // 挑选最大值
                } else { // 栈空了
                    stack.push(i); // 入栈充当参照物
                }
            };
            console.log(stack);
        }
        return maxLen;
    };
    longestValidParentheses('()()((()())')
})();

; (function () {
    return


    function longestValidParentheses(s) {
        let left = 0, right = 0, maxlength = 0;
        for (let i = 0; i < s.length; i++) {
            if (s.charAt(i) == '(') {
                left++;
            } else {
                right++;
            }
            if (left == right) {
                maxlength = Math.max(maxlength, 2 * right);
            } else if (right > left) {
                left = right = 0;
            }
        }
        left = right = 0;
        for (let i = s.length - 1; i >= 0; i--) {
            if (s[i] == '(') {
                left++;
            } else {
                right++;
            }
            console.log(left, right);
            if (left == right) {
                maxlength = Math.max(maxlength, 2 * left);
            } else if (left > right) {
                left = right = 0;
            }
        }
        return maxlength;
    }
    console.log(longestValidParentheses('())('));


})();